package com.tangpian.sna.core.analysis.polarity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tangpian.sna.core.analysis.Analyzer;
import com.tangpian.sna.core.analysis.polarity.dao.ItemSentimentScoreDao;
import com.tangpian.sna.core.analysis.polarity.model.ItemSentimentScore;
import com.tangpian.sna.core.dao.ItemDao;
import com.tangpian.sna.core.model.Item;
import com.tangpian.sna.core.tokenizer.AnsjTokenizer;
import com.tangpian.sna.core.tokenizer.Tokenizer;
import com.tangpian.sna.core.util.FileUtil;

/**
 * 
 * @author shydow
 * 
 * @param <T>
 */
@Component
public class PolarityAnalyzer<T extends Item> implements Analyzer<T> {

	private Logger logger = LoggerFactory.getLogger(PolarityAnalyzer.class);

	private static final String polarityFilePath = "res/polarity/polarity";

	private Map<String, Double> polaritis = new HashMap<String, Double>();

	private Tokenizer tokenizer = new AnsjTokenizer();

	@Autowired
	private ItemSentimentScoreDao<ItemSentimentScore> itemSentimentScoreDao;

	@Override
	public void analysis(List<T> items, String taskId) {
		List<ItemSentimentScore> itemSentimentScores = new ArrayList<ItemSentimentScore>();

		for (T item : items) {
			double score = 0;
			String[] words = tokenizer.segmentation(item.getContent()).split(
					" ");
			for (int i = 0; i < words.length; i++) {
				if (polaritis.get(words[i].toLowerCase()) != null) {
					score += polaritis.get(words[i].toLowerCase());
				}
			}
			itemSentimentScores.add(new ItemSentimentScore(item.getId(), score,
					taskId));
		}

		itemSentimentScoreDao.save(itemSentimentScores);
	}

	@PostConstruct
	private void init() {
		List<String> lines = FileUtil.readFile(
				FileUtil.getFilePathFromClasspath(polarityFilePath), "utf-8");
		for (String string : lines) {
			logger.info("string:" + string);
			String word = string.split("	")[0];
			double score = Double.parseDouble(string.split("	")[1]);
			polaritis.put(word, score);
		}
	}

}
